package com.datasecops.scannerservices.operation;

import com.datasecops.scannerservices.db.ESClient;
import com.datasecops.scannerservices.entity.CommonParam;
import com.datasecops.scannerservices.service.ScanDataProcessServers;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * ElasticSearch操作类
 * @author: GeXiaoLong
 * @time: 2022/10/20 10:34
 */
@Service
@Slf4j
public class ESClientOperation {

    @Resource
    private  ScanDataProcessServers dataProcessServers;

    public List<String> getTablesByDBName(CommonParam param, String Instance){

        return ESClient.getAllCollections(Instance);
    }

//     static RestHighLevelClient client = ESClient.getClient(ip,post);
//    static RestHighLevelClient client = ESClient.client(ip,post,userName,password);
    //static String index = "person";
    //static String index = "twitter";
    //static String type = "_doc";

    // Java实现scroll分页

    public  Boolean getDBResult(CommonParam param, CommonParam commonParam, String instance, String jobId, String jobName, String scannerID,
                                String linage) {
        RestHighLevelClient client;
        if (param.getPassword().equalsIgnoreCase("nouserdefault")){
             //client = ESClient.client(param.getIp(),param.getPort(),param.getUserName(),param.getPassword());
            client = ESClient.getClient(param.getIp(),param.getPort());
        }else {
            client = ESClient.client(param.getIp(),param.getPort(),param.getUserName(),param.getPassword());
             //client = ESClient.getClient(param.getIp(),param.getPort());
        }

        //1. 创建SearchRequest
        SearchRequest request = new SearchRequest(instance);
       // request.types(type);

        //2. 指定scroll信息
        request.scroll(TimeValue.timeValueMinutes(1L));

        //3. 指定查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.size(1000);
        //builder.sort("fee", SortOrder.DESC);
        builder.query(QueryBuilders.matchAllQuery());
        request.source(builder);
        try {
            //4. 获取返回结果scrollId，source
            SearchResponse resp = client.search(request, RequestOptions.DEFAULT);

            String scrollId = resp.getScrollId();
            System.out.println("----------首页---------");
            List<String> list = new ArrayList<>();
            List<String> lists = new ArrayList<>();
            int batch = 0;
            for (SearchHit hit : resp.getHits().getHits()) {
                System.out.println(hit.getSourceAsMap());
                list.add(String.valueOf((hit.getSourceAsMap())));
                System.out.println(list);
            }
            System.out.println("我好开心啊");
            //数据操作
            batch++;
            dataProcessServers.tradingData(param, commonParam, list, batch, true, "key_data_", ".txt", jobId, jobName, scannerID, linage);
            while (true) {
                //5. 循环 - 创建SearchScrollRequest
                SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);

                //6. 指定scrollId的生存时间
                scrollRequest.scroll(TimeValue.timeValueMinutes(1L));

                //7. 执行查询获取返回结果
                SearchResponse scrollResp = client.scroll(scrollRequest, RequestOptions.DEFAULT);

                //8. 判断是否查询到了数据，输出
                SearchHit[] hits = scrollResp.getHits().getHits();
                if (hits != null && hits.length > 0) {
                    System.out.println("----------下一页---------");
                    for (SearchHit hit : hits) {
                        System.out.println(hit.getSourceAsMap());
                        lists.add(String.valueOf(hit.getSourceAsMap()));
                    }
                    System.out.println("123456");
                    batch++;
                    dataProcessServers.tradingData(param, commonParam, lists, batch, true, "key_data_", ".txt", jobId, jobName,
                            scannerID, linage);
                    lists.clear();
                } else {
                    //9. 判断没有查询到数据-退出循环
                    System.out.println("----------结束---------");
                    break;
                }
            }


            //10. 创建CLearScrollRequest
            ClearScrollRequest clearScrollRequest = new ClearScrollRequest();

            //11. 指定ScrollId
            clearScrollRequest.addScrollId(scrollId);

            //12. 删除ScrollId
            ClearScrollResponse clearScrollResponse = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);

            //13. 输出结果
            System.out.println("删除scroll：" + clearScrollResponse.isSucceeded());

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return true;
    }

    public static void main(String[] args) throws IOException {
        //createIndex();
        //exists();
        //scrollQuery();
        //termQuery();
    }




}
